/**
 * Cesium Map Service
 * leaflet地图控制服务，添加图层、添加几何体和视图，操作地图
 */

 angular.module('ZJPC')
 .service('CesiumService', ['$rootScope', '$timeout', 'ModalService', 'DataService', 'CONST', CesiumService]);


function CesiumService($rootScope, $timeout, ModalService, DataService, CONST) {
	var that = this;
	var viewer;
	var angleOfView = new Cesium.NearFarScalar(80.0, 3.0, 800.0, 0.6);
	var destination = Cesium.Cartesian3.fromDegrees(120.1438728940547,30.1777954232, 400);
	var orientation = {
        heading : Cesium.Math.toRadians(-200.0), // 方向
        pitch : Cesium.Math.toRadians(-40.0),// 倾斜角度
        roll : 0.0
    };

	//飞机实体
	var plane_entity;
	//3D 建筑模型
	var building_3D = new Cesium.Cesium3DTileset({
	    // url: 'Build/all_fix/6_lod/tileset.json'
	    url: 'Build/obl/tileset.json'
	});
  	//天地图底图，矢量图和卫星图
	var imageryProvider_vec = new Cesium.WebMapTileServiceImageryProvider({
		url: "http://t0.tianditu.com/vec_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=vec&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles",        
	    layer: "tdtVecBasicLayer",        
	    style: "default",        
	    format: "image/jpeg",        
	    tileMatrixSetID: "GoogleMapsCompatible",        
	    show: false    
	});
  	var imageryProvider_img = new Cesium.WebMapTileServiceImageryProvider({
	    url: "http://{s}.tianditu.com/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles",        
	    layer: "img",        
	    style: "default",        
	    format: "tiles",        
	    tileMatrixSetID: "w",
	    subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7'],
	    maximumLevel: 18,
	    // tilingScheme : new Cesium.GeogaaraphicTilingScheme(),
	    // tileMatrixLabels: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18']
    })
	//重置视角
	that.reset = function () {
		viewer.camera.flyTo({
		    destination :  destination, // 设置位置
		    orientation: orientation
		});
	}
	$timeout(this.reset, 8000);

	that.init = function (){

	 	// Cesium.Camera.DEFAULT_VIEW_RECTANGLE = Cesium.Rectangle.fromDegrees(120.148532, 30.169596, 120.151653, 30.172729);
	 	// Cesium.Camera.DEFAULT_VIEW_FACTOR = 0;
	 	var tms = new Cesium.UrlTemplateImageryProvider({
	 		url : CONST.tileUrl,
	 		maximumLevel : 18
	 	});
	 	
		//矢量图
		viewer = new Cesium.Viewer("cesiumContainer", {
			animation: false,  //是否显示动画控件    
			shadows: false,
			baseLayerPicker: false, //是否显示图层选择控件    
			geocoder: false, //是否显示地名查找控件    
			timeline: false, //是否显示时间线控件    
			sceneModePicker: false, //是否显示投影方式控件    
			navigationHelpButton: false, //是否显示帮助信息控件    
			infoBox: false,  //是否显示点击要素之后显示的信息 
			homeButton: false,  //是否显示home按键
			selectionIndicator: false,	//设置绿色框框不可见
			// imageryProvider: imageryProvider_vec
			imageryProvider: imageryProvider_img
		});

    //加载底图
    viewer.imageryLayers.addImageryProvider(new Cesium.UrlTemplateImageryProvider({
        url: 'Build/dataset/{z}/{x}/{y}.png',
        tilingScheme: new Cesium.WebMercatorTilingScheme()
    }));

		// 创建一个椭球
		/*var entities = viewer.entities;
		var stripeMaterial = new Cesium.StripeMaterialProperty({
		    evenColor : Cesium.Color.WHITE.withAlpha(0.5),
		    oddColor : Cesium.Color.BLUE.withAlpha(0.5),
		    repeat : 5.0
		});*/

		/*entities.add({
	        position : Cesium.Cartesian3.fromDegrees(120.147896, 30.173778, 20),
	        ellipsoid : {
	            radii : new Cesium.Cartesian3(15.0, 15.0, 20.0),
	            material : Cesium.Color.fromRandom({alpha : 1.0}),
	            billboard : {
			    	image : '/img/摄像头.png', 
			    	width : 30, 
			    	height : 40,
			    	scaleByDistance : angleOfView
		   	 	}
	        }
	    });*/

	 	/*for(var i = 0; i < 50; i++){
	 		var entities = viewer.entities;
		    var center = Cesium.Cartesian3.fromDegrees(120.145563, 30.174691, i);
		    var heading = Cesium.Math.PI_OVER_FOUR * 2;
		    var pitch = Cesium.Math.PI;
		    var roll = Cesium.Math.PI_OVER_TWO;	
		    var hpr = new Cesium.HeadingPitchRoll(heading, pitch, roll);
		    var quaternion = Cesium.Transforms.headingPitchRollQuaternion(center, hpr);
		    entity = viewer.entities.add({
				position : center, 
				// scale : 0.05,
				orientation : quaternion,
		    	model : {
			    	uri : '/img/gltf/kakou.gltf', 
			    	scale: 0.02,	
		            scaleByDistance : angleOfView
		   	 	}
			});
	 	}*/
	    
		
		viewer.scene.globe.enableLighting = false; 

		//初始化时镜头的视角
		// viewer.camera.setView({
		//     destination :  destination, // 设置位置
		//     orientation: orientation
		// });

		//相机允许缩小放大的最大值
		var scene = viewer.scene;
		var controller = scene.screenSpaceCameraController;

		controller.minimumZoomDistance = 5;
		// controller.maximumZoomDistance = 1000;

	}

	// 初始化页面
	that.init();

	var total = [];

	//设置没有建筑实体时的logo
	that.setLogo = function (){
		var logoName = ['超市', '第二食堂', '第一食堂', '警官苑', '警官苑餐厅', '教学楼', '礼堂', '宿舍楼13幢', '宿舍楼14幢',
						'宿舍楼15幢', '宿舍楼16幢', '宿舍楼17幢', '宿舍楼18幢', '图书馆', '综合楼', '专家楼', '战训楼', '警务保障楼'];
		var position = [
			[120.143867, 30.172989],
			[120.144105, 30.173352],
			[120.144188, 30.173064],
			[120.143586, 30.173710],
			[120.143463, 30.174025],
			[120.145825, 30.173600],
			[120.144222, 30.173229],
			[120.144027, 30.172686],
			[120.144553, 30.172805],
			[120.144141, 30.172382],
			[120.144621, 30.172485],
			[120.144214, 30.172083],
			[120.144680, 30.172178],
			[120.146095, 30.172655],
			[120.144529, 30.174265],
			[120.144292, 30.171722],
			[120.148099, 30.175121],
			[120.146043, 30.172167]
		];
		var imgUrl = ['/img/build/cs.png', '/img/build/dest.png', '/img/build/dyst.png', '/img/build/jgy.png', '/img/build/jgyct.png', 
					  '/img/build/jxl.png', '/img/build/lt.png', '/img/build/ss13.png', '/img/build/ss14.png', '/img/build/ss15.png', 
					  '/img/build/ss16.png', '/img/build/ss17.png', '/img/build/ss18.png', '/img/build/tsg.png', '/img/build/zhl.png', 
					  '/img/build/zjl.png', '/img/build/zxl.png', '/img/build/jwbzl.png'];
		for(var i = 0; i < 18; i++){
			that.logo = viewer.entities.add({
				id : logoName[i], 
				show : true, 
				position : Cesium.Cartesian3.fromDegrees(position[i][0], position[i][1]), 
		    	billboard : {
			    	image : imgUrl[i], 
			    	width : 87, 
			    	height : 19,
			    	scaleByDistance : angleOfView
		   	 	}
			});
			total.push(that.logo);
		}
	}

	that.setLogo();

	//移除建筑标牌的方法
	function changeBuildLogo (state){
		for(var i = 0; i < total.length; i++){
			total[i].show = state;
		}

	}

	var tileset = [];
	//加载建筑的方法
	that.addBuild = function (){
		for (var i = 1; i < 75; i++) {
		    tileset[i - 1] = viewer.scene.primitives.add(new Cesium.Cesium3DTileset({
		        url: 'Build/3dmodel/' + i + '_lod/tileset.json'
		    }));

		    tileset[i - 1].readyPromise.then(function(tileset) {
		        var cartographic = Cesium.Cartographic.fromCartesian(tileset.boundingSphere.center);
		        var surface = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, 0.0);
		        var offset = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, -28);
		        var translation = Cesium.Cartesian3.subtract(offset, surface, new Cesium.Cartesian3());
		        tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
		    });
		}
		for(var i = 0; i < tileset.length; i++){
			tileset[i].show = false;
		}
	}

	that.addBuild();

	that.checkShowBuilding = function (value) {

		/*var bulidTotal = ['警官苑', '食堂', '战训楼', '校外超市', '校大门', '图书馆', '拳击场', '篮球场', '模拟现场', '教学楼', '学生公寓', '专家楼'];
		function add3DTiles (num){
			building_3D = viewer.scene.primitives.add(new Cesium.Cesium3DTileset({
			    url: 'Build/3dmodel/' + (num + 1) + '_lod'+ '/tileset.json'
			}));
			building_3D.id = bulidTotal[i];

			building_3D.readyPromise.then(function(tileset) {
				var cartographic = Cesium.Cartographic.fromCartesian(tileset.boundingSphere.center);
				var surface = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, 0.0);
				var offset = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, -28);
				var translation = Cesium.Cartesian3.subtract(offset, surface, new Cesium.Cartesian3());
				tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
			});
		}*/
		if(value) {
			changeBuildLogo(false);
			changeBuild(true);
		}
		else {
			changeBuild(false);
			changeBuildLogo(true);

		}
	}

	//隐藏建筑体的操作
	function changeBuild (state){
		for (var i = 0; i < tileset.length; i++) {
			tileset[i].show = state;
		}
	}

	//添加室外三维实体点位的方法
	that.addEntity = function (name, coord, type, id, imgUrl, height, angle){
		var totalArray = [];
		
		for (var i = 0; i < coord.length; i++) {
			var cameraL = coord[i][0];
			var cameraR = coord[i][1];
			if(cameraL != null && cameraR != null){
				var center = Cesium.Cartesian3.fromDegrees(cameraL, cameraR, height[i]);
				var heading = Cesium.Math.PI_OVER_FOUR * angle[i];
				var pitch = Cesium.Math.PI;
				var roll = Cesium.Math.PI_OVER_TWO;	
				var hpr = new Cesium.HeadingPitchRoll(heading, pitch, roll);
				var quaternion = Cesium.Transforms.headingPitchRollQuaternion(center, hpr);

				that.faceCamera = viewer.entities.add({
					id : type + id[i], 
					name : name[i],
					show : false,
					position : center, 
					orientation : quaternion,
			    	model : {
				    	uri : imgUrl, 
				    	scale: 0.01,
				    	// minimumPixelSize: 16,
			            scaleByDistance : angleOfView
			   	 	}
				});
				totalArray.push(that.faceCamera);
			}
		};
		return totalArray;
	}
	
	//添加室外点位的方法
	that.addFacility = function (name, coord, type, id, imgUrl){

		var totalArray = [];
		for (var i = 0; i < coord.length; i++) {
			var cameraL = coord[i][0];
			var cameraR = coord[i][1];
			if(cameraL != null && cameraR != null){
				that.faceCamera = viewer.entities.add({
					id : type + id[i], 
					name : name[i],
					show : false, 
					position : Cesium.Cartesian3.fromDegrees(cameraL, cameraR), 
			    	billboard : {
				    	image : imgUrl, 
				    	width : 16, 
				    	height : 20.4,
				    	scaleByDistance : angleOfView,
				    	horizontalOrigin : Cesium.HorizontalOrigin.CENTER,
				    	verticalOrigin : Cesium.VerticalOrigin.BOTTOM
			   	 	}
				});
				totalArray.push(that.faceCamera);
			}
		};
		return totalArray;
	}

	getTree = {};
	//设置室外点位
	that.spotSetting = function (){

		DataService.getTreeData(callback);
		function callback(respon){
			// console.log(respon,'t');
		  	getTree = respon;
		  	that.belong = {
		  		"综合楼": {
		  			"wifi": [],
		  			"monitor": [],
		  			"face": [],
		  			"bayonet": []
		  		},
		  		"警官苑": {
		  			"wifi": [],
		  			"monitor": [],
		  			"face": [],
		  			"bayonet": []
		  		},
		  		"食堂": {
		  			"wifi": [],
		  			"monitor": [],
		  			"face": [],
		  			"bayonet": []
		  		},
		  		"宿舍楼13幢": {
		  			"wifi": [],
		  			"monitor": [],
		  			"face": [],
		  			"bayonet": []
		  		},
		  		"宿舍楼14幢": {
		  			"wifi": [],
		  			"monitor": [],
		  			"face": [],
		  			"bayonet": []
		  		},
		  		"宿舍楼15幢": {
		  			"wifi": [],
		  			"monitor": [],
		  			"face": [],
		  			"bayonet": []
		  		},
		  		"宿舍楼16幢": {
		  			"wifi": [],
		  			"monitor": [],
		  			"face": [],
		  			"bayonet": []
		  		},
		  		"宿舍楼18幢": {
		  			"wifi": [],
		  			"monitor": [],
		  			"face": [],
		  			"bayonet": []
		  		},
		  		"专家楼": {
		  			"wifi": [],
		  			"monitor": [],
		  			"face": [],
		  			"bayonet": []
		  		},
		  		"教学楼": {
		  			"wifi": [],
		  			"monitor": [],
		  			"face": [],
		  			"bayonet": []
		  		},
		  		"图书馆": {
		  			"wifi": [],
		  			"monitor": [],
		  			"face": [],
		  			"bayonet": []
		  		},
		  		"警务保障楼": {
		  			"wifi": [],
		  			"monitor": [],
		  			"face": [],
		  			"bayonet": []
		  		},
		  		"战训楼": {
		  			"wifi": [],
		  			"monitor": [],
		  			"face": [],
		  			"bayonet": []
		  		}
		  	}

		  	/*that.setH = function (height){
		  		console.log(height);
		  	}*/

	  		
	  		setMonitor();
	  		setFace();
	  		setWifi();
	  		setIcard();
	  		setBayonet();

  			function setMonitor(){
  				var monitorBox = [];
  		  	 	var cameraName = [];
  		  	 	var mid= [];
  		  	 	var cameraPos = [];
  		  	 	var type = 'jj+';
  		  	 	
  		  	 	for(var i = 0; i < respon.jiankong.length; i++){
  		  	 		if(respon.jiankong[i].buildName == '' || respon.jiankong[i].buildName == null){
  		  		 		cameraName.push(respon.jiankong[i].text);
  		  		 		mid.push(respon.jiankong[i].id);
  		  		 		cameraPos.push([respon.jiankong[i].camerJd, respon.jiankong[i].camerWd]);
  		  			}else{
  		  				if(that.belong[respon.jiankong[i].buildName] != undefined){
			 				that.belong[respon.jiankong[i].buildName].monitor.push(respon.jiankong[i]);
  		  				}
			 		}
  		  	 	}
  		   		var url = '/img/ico/monitor.png';
  		  		that.monitorBox = that.addFacility(cameraName, cameraPos, type, mid, url);
  			}

  			that.setMonitor = function(){
  				var monitorBox = [];
  		  	 	var cameraName = [];
  		  	 	var mid= [];
  		  	 	var cameraPos = [];
  		  	 	var type = 'jj+';
  		  	 	var angle = [];
  		  	 	var height = [];
  		  	 	
  		  	 	for(var i = 0; i < respon.jiankong.length; i++){
  		  	 		if(respon.jiankong[i].buildName == '' || respon.jiankong[i].buildName == null){
  		  		 		cameraName.push(respon.jiankong[i].text);
  		  		 		mid.push(respon.jiankong[i].id);
  		  		 		cameraPos.push([respon.jiankong[i].camerJd, respon.jiankong[i].camerWd]);
  		  		 		if(respon.jiankong[i].deviceAngle == null){
  		  		 			respon.jiankong[i].deviceAngle = 0;
  		  		 		}
  		  		 		angle.push(respon.jiankong[i].deviceAngle);
  		  		 		if(respon.jiankong[i].deviceHigh == null){
  		  		 			respon.jiankong[i].deviceHigh = 0;
  		  		 		}
  		  		 		height.push(respon.jiankong[i].deviceHigh);
  		  			}else{
  		  				if(that.belong[respon.jiankong[i].buildName] != undefined){
			 				that.belong[respon.jiankong[i].buildName].monitor.push(respon.jiankong[i]);
  		  				}
			 		}
  		  	 	}
  		   		var url = '/img/gltf/kakou.gltf';
  		  		that.monitorBox = that.addEntity(cameraName, cameraPos, type, mid, url, height, angle);
  			}

  			// that.setMonitor();

  			that.setNoHeightMonitor = function(){
  				var monitorBox = [];
  		  	 	var cameraName = [];
  		  	 	var mid= [];
  		  	 	var cameraPos = [];
  		  	 	var type = 'jj+';
  		  	 	var angle = [];
  		  	 	var height = [];
  		  	 	
  		  	 	for(var i = 0; i < respon.jiankong.length; i++){
  		  	 		if(respon.jiankong[i].buildName == '' || respon.jiankong[i].buildName == null){
  		  		 		cameraName.push(respon.jiankong[i].text);
  		  		 		mid.push(respon.jiankong[i].id);
  		  		 		cameraPos.push([respon.jiankong[i].camerJd, respon.jiankong[i].camerWd]);
  		  		 		if(respon.jiankong[i].deviceAngle == null){
  		  		 			respon.jiankong[i].deviceAngle = 0;
  		  		 		}
  		  		 		angle.push(respon.jiankong[i].deviceAngle);
  		  		 		if(respon.jiankong[i].deviceHigh == null){
  		  		 			respon.jiankong[i].deviceHigh = 0;
  		  		 		}
  		  		 		height.push(respon.jiankong[i].deviceHigh);
  		  			}else{
  		  				if(that.belong[respon.jiankong[i].buildName] != undefined){
			 				that.belong[respon.jiankong[i].buildName].monitor.push(respon.jiankong[i]);
  		  				}
			 		}
  		  	 	}
  		   		var url = '/img/gltf/kakou.gltf';
  		  		that.monitorBox = that.addEntity(cameraName, cameraPos, type, mid, url, 0, angle);
  			}

  			// that.setNoHeightMonitor();

  			function setFace(){
				var faceBox = [];
			 	var faceName = [];
			 	var facePlace = [];
			 	var type = 'rr+';
			 	var fid = [];
			 	for(var i = 0; i < respon.renlian.length; i++){
			 		if(respon.renlian[i].buildName == '' || respon.renlian[i].buildName == null){
			 			faceName.push(respon.renlian[i].text);
				 		fid.push(respon.renlian[i].id);
				 		facePlace.push([respon.renlian[i].camerJd, respon.renlian[i].camerWd]);
			 		}else{
			 			that.belong[respon.renlian[i].buildName].face.push(respon.renlian[i]);
			 		}
			 	}
		 		var url = '/img/ico/face.png';
				that.faceBox = that.addFacility(faceName, facePlace, type, fid, url);	
  			}

  			function setWifi(){
  				var wifiBox = [];
			 	var wifiName = [];
			 	var wifiPlace = [];
			 	var type = 'ww+';
			 	var wid = [];
			 	for(var i = 0; i < respon.wifi.length; i++){
			 		if(respon.wifi[i].buildName == '' || respon.wifi[i].buildName == null){
			 			wifiName.push(respon.wifi[i].text);
				 		wid.push(respon.wifi[i].id);
				 		wifiPlace.push([respon.wifi[i].camerJd, respon.wifi[i].camerWd]);
			 		}else{
			 			that.belong[respon.wifi[i].buildName].wifi.push(respon.wifi[i]);
			 		}
			 	}
		 		var url = '/img/ico/wifi.png';
				that.wifiBox = that.addFacility(wifiName, wifiPlace, type, wid, url);
  			}

  			function setIcard(){
				var icardBox = [];
			 	var icardName = [];
			 	var icardPlace = [];
			 	var type = 'yy+';
			 	var cid = [];
			 	for(var i = 0; i < respon.ykt.length; i++){
			 		if(respon.ykt[i].buildName == '' || respon.ykt[i].buildName == null){
			 			icardName.push(respon.ykt[i].text);
				 		cid.push(respon.ykt[i].id);
				 		icardPlace.push([respon.ykt[i].camerJd, respon.ykt[i].camerWd]);
			 		}
			 	}
		 		var url = '/img/ico/icard.png';
				that.icardBox = that.addFacility(icardName, icardPlace, type, cid, url);
  			}

  			function setBayonet(){
				var bayonetBox = [];
			 	var bayonetName = [];
			 	var bayonetPlace = [];
			 	var type = 'kk+';
			 	var bid = [];
			 	for(var i = 0; i < respon.kakou.length; i++){
			 		if(respon.kakou[i].buildName == '' || respon.kakou[i].buildName == null){
			 			bayonetName.push(respon.kakou[i].text);
				 		bid.push(respon.kakou[i].id);
				 		bayonetPlace.push([respon.kakou[i].camerJd, respon.kakou[i].camerWd]);
			 		}else{
			 			that.belong[respon.kakou[i].buildName].bayonet.push(respon.kakou[i]);
			 		}
			 	}
		 		var url = '/img/ico/bayonet.png';
				that.bayonetBox = that.addFacility(bayonetName, bayonetPlace, type, bid, url);
  			}
		}
	}
	that.spotSetting();

	//移除页面中的全部实体
	that.removeAllEntity = function (){
		viewer.entities.removeAll();
	}

	//设置室内点位
	that.addIndoorEqui = function (){
		DataService.getTreeData(callback);
		function callback(response){

			getBuild(response.jiankong);
			getBuild(response.kakou);
			getBuild(response.renlian);
			getBuild(response.ykt);
			getBuild(response.wifi);

		}
	}
	that.addIndoorEqui();

	var byBuilding = [];
	function getBuild (type){
		for (var i = 0; i < type.length; i++) {
			if (type[i].buildName != null) {
				byBuilding.push(type[i]);	
			}
		}
	}

	//鼠标移到建筑变色以及显示建筑或设备的名称
	that.changeColor = function (){

		var nameOverlay = document.createElement('div');
		viewer.container.appendChild(nameOverlay);
		nameOverlay.className = 'backdrop';
		nameOverlay.style.display = 'none';
		nameOverlay.style.position = 'absolute';
		nameOverlay.style.bottom = '0';
		nameOverlay.style.left = '0';
		nameOverlay.style['pointer-events'] = 'none';
		nameOverlay.style.padding = '4px';
		nameOverlay.style.backgroundColor = 'white';

		var selected = {
			feature: undefined,
			originalColor: new Cesium.Color()
		};

		var highlighted = {
			feature: undefined,
			originalColor: new Cesium.Color()
		};

		var selectedEntity = new Cesium.Entity();

		viewer.screenSpaceEventHandler.setInputAction(function onMouseMove(movement) {

		    // 如果之前突出显示了一个特性，则取消高亮显示
		    if (Cesium.defined(highlighted.feature)) {
			    if(highlighted.feature.id.polygon != undefined){
			    	highlighted.feature.id.polygon.material = highlighted.originalColor;
			    	highlighted.feature = undefined;
			    }
		  	}

		  	var nameOver = document.getElementsByClassName("trackMessage");
		    var pickedFeature = viewer.scene.pick(movement.endPosition);
		    // console.log(pickedFeature,1);
		    if (!Cesium.defined(pickedFeature)) {
		        nameOverlay.style.display = 'none';
		    	nameOver[0].style.display = 'none';
		    	$rootScope.$broadcast('nameOver', {});
		        return;
		    }
		    
		    // 鼠标移到建筑或设备显示建筑或设备的名称
		    nameOverlay.style.display = 'block';
		    nameOverlay.style.bottom = viewer.canvas.clientHeight - movement.endPosition.y + 'px';
		    nameOverlay.style.left = movement.endPosition.x + 'px';

		    if(pickedFeature.id){
		    	var name = pickedFeature.id.name;
			    if(pickedFeature.id.id.substr(0, 5) == 'point'){
			    	nameOverlay.style.display = 'none';
				    nameOver[0].style.display = 'block';
			        nameOver[0].style.bottom = viewer.canvas.clientHeight - movement.endPosition.y - 20 + 'px';
			        nameOver[0].style.left = movement.endPosition.x - 75 + 'px';
	          		$rootScope.$broadcast('nameOver', getTrackPointInfoById(pickedFeature.id.id));
				}
				if(pickedFeature.id.id == 'track'){
					nameOverlay.style.display = 'none';
				}
		    }else{
		    	var name = pickedFeature.primitive.id;
		    }
		    nameOverlay.textContent = name;
		    //鼠标移到轨迹点显示轨迹点详细信息
		    if(pickedFeature.id.id.substr(0, 5) == 'point'){

		    	nameOverlay.style.display = 'none';
			    nameOver[0].style.display = 'block';
		        nameOver[0].style.bottom = viewer.canvas.clientHeight - movement.endPosition.y + 20 + 'px';
		        nameOver[0].style.left = movement.endPosition.x - 75 + 'px';
          		$rootScope.$broadcast('nameOver', getTrackPointInfoById(pickedFeature.id.id));
			}
			if(pickedFeature.id.id == 'track'){
				nameOverlay.style.display = 'none';
			}
		}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
	}
	that.changeColor();

	that.changeBuildLight = function (){
		// 鼠标移动到建筑上后，隐藏或高亮显示
		var current = {
		    feature: undefined,
		    selected: false
		};

		var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
		handler.setInputAction(
		    function(movement) {
		        var feature = viewer.scene.pick(movement.endPosition);
		        if (feature !== undefined && feature.primitive instanceof Cesium.Cesium3DTileset) {
		            // 隐藏建筑
		            // feature.primitive.show = false;
		            // 高亮显示
		            if (Cesium.defined(current.feature) && (current.feature !== feature)) {
		                current.feature.content._model.color = Cesium.Color.fromAlpha(Cesium.Color.WHITE, 1);
		                current.feature.primitive.colorBlendAmount = 1;
		                current.feature.content._model.colorBlendMode = Cesium.Cesium3DTileColorBlendMode.HIGHLIGHT;
		                current.feature = undefined;
		            }
		            if (Cesium.defined(feature) && (feature !== current.feature)) {
		                current.feature = feature;
		                current.selected = true;
		                current.feature.content._model.color = Cesium.Color.fromAlpha(Cesium.Color.YELLOW, 1);
		                current.feature.primitive.colorBlendAmount = 1;
		                current.feature.content._model.colorBlendMode = Cesium.Cesium3DTileColorBlendMode.HIGHLIGHT;
		            }
		        } else if (current.selected) {
		            current.feature.content._model.color = Cesium.Color.fromAlpha(Cesium.Color.WHITE, 1);
		            current.feature.primitive.colorBlendAmount = 1;
		            current.feature.content._model.colorBlendMode = Cesium.Cesium3DTileColorBlendMode.HIGHLIGHT;
		            current.feature = undefined;
		            current.selected = false;
		        }
		    },Cesium.ScreenSpaceEventType.MOUSE_MOVE
		);
	}

	that.changeBuildLight();

	//控制实体隐藏与否
	that.setEntityStatus = function (array, status){
		for (var i = 0; i < array.length; i++) {
			array[i].show = status;
		}
	}

	var check_build_name = '';

	//点击建筑显示室内设备轮盘
	that.clickBuildings = function (){
		viewer.screenSpaceEventHandler.setInputAction(function(movement) {

			var feature = viewer.scene.pick(movement.position);
			var nameOverlay = document.getElementsByClassName("indoorEquipment");
			// console.log(feature,1);
			if(feature.id.id != undefined){
				var check_build_name = feature.id.id;
				$rootScope.$broadcast("check_build_name", check_build_name);
			}

			if(feature.id.id == "综合楼" || feature.id.id == "第一食堂" || feature.id.id == "第二食堂" || feature.id.id == "图书馆" || 
				feature.id.id == "宿舍楼13幢" || feature.id.id == "宿舍楼14幢" || feature.id.id == "宿舍楼15幢" || 
				feature.id.id == "宿舍楼16幢" || feature.id.id == "宿舍楼18幢" || feature.id.id == "警官苑" || 
				feature.id.id == "警官苑餐厅" ||  feature.id.id == "战训楼" || feature.id.id == "专家楼" || 
				feature.id.id == "综合楼" || feature.id.id == "礼堂" || feature.id.id == "超市" || feature.id.id == "警务保障楼"){
				
				if(that.belong[feature.id.id].monitor != '' || that.belong[feature.id.id].face != '' || 
				that.belong[feature.id.id].wifi != '' || that.belong[feature.id.id].bayonet != ''){
					var checkObj = {
						belong: that.belong,
						buildName: feature.id.id
					};
					$rootScope.$broadcast("belong", checkObj);
					nameOverlay[0].style.display = 'block';
					nameOverlay[0].style.bottom = viewer.canvas.clientHeight - movement.position.y - 100 + 'px';
			        nameOverlay[0].style.left = movement.position.x - 100 + 'px';		
				}
			}

		}, Cesium.ScreenSpaceEventType.LEFT_CLICK);

		$(".indoorEquipment").on("mouseleave", function (){
			this.style.display = 'none';
		});
	}

	that.clickBuildings();

	//取消双击事件的绑定
	viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);

	//点击相关设备的操作
	that.clickThings = function(){

		var scene = viewer.scene;
		var handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
		handler.setInputAction(function (movement) {
		    var pickedObject = scene.drillPick(movement.position);
		    var checkName = -1;
		    var checked = -1;
		    if (Cesium.defined(pickedObject)) {
	    		checked = pickedObject[0].id.id;
	    		checkName = pickedObject[0].id.name;
	    		var obj = {
	    			checked: checked,
	    			checkName: checkName
	    		};
		        if(checked.substr(0, 2) == 'jj'){
		    	  	ModalService.openModal(checked);
		        }else if(checked.substr(0, 2) == 'kk'){
		        	ModalService.openModalFunc(obj, 'templates/region/bayonet.html', 'BayonetController');
		        }else if(checked.substr(0, 2) == 'rr'){
		        	ModalService.openModalFunc(obj, 'templates/region/face.html', 'FaceController');
		        }else if(checked.substr(0, 2) == 'yy'){
		        	ModalService.openModalFunc(obj, 'templates/region/icard.html', 'IcardController');
		        }else if(checked.substr(0, 2) == 'ww'){
		        	ModalService.openModalFunc(obj, 'templates/region/wifi.html', 'WifiController');
		        }
		    }
		}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
	}

  	//添加3D飞机模型   仅显示用
	that.addPlane = function() {

	    //Set bounds of our simulation time   飞机飞行动画
	    var start = Cesium.JulianDate.fromDate(new Date(2017, 12, 01, 08));
	    var stop = Cesium.JulianDate.addSeconds(start, 420, new Cesium.JulianDate());

	    //Make sure viewer is at the desired time.
	    viewer.clock.startTime = start.clone();
	    viewer.clock.stopTime = stop.clone();
	    viewer.clock.currentTime = start.clone();
	    viewer.clock.clockRange = Cesium.ClockRange.LOOP_STOP; //Loop at the end
	    viewer.clock.multiplier = 25;

	    //Set timeline to simulation bounds
	    // viewer.timeline.zoomTo(start, stop);

	    //Generate a random circular pattern with varying heights.
	    function computeCirclularFlight(lon, lat, radius) {
	        
	        var property = new Cesium.SampledPositionProperty();
	        for (var i = 0; i <= 360; i += 10) {
	            var radians = Cesium.Math.toRadians(i);
	            var time = Cesium.JulianDate.addSeconds(start, i, new Cesium.JulianDate());
	            var position = Cesium.Cartesian3.fromDegrees(lon + (radius * 0.12 * Math.cos(radians)), 
	              lat + (radius * 0.095 * Math.sin(radians)), 80 + 60 * Math.sin(radians));
	            property.addSample(time, position);

	            //Also create a point for each sample we generate.  为生成的样本创建点
	            // viewer.entities.add({
	            //     position : position,
	            //     point : {
	            //         pixelSize : 8,
	            //         color : Cesium.Color.TRANSPARENT,
	            //         outlineColor : Cesium.Color.DARKGREY,
	            //         outlineWidth : 3
	            //     }
	            // });
	        }
	        return property;
	    }

	    //Compute the entity position property.
	    var position = computeCirclularFlight(120.14608434683515,30.1737724116, 0.02);

	    //Actually create the entity
	    plane_entity = viewer.entities.add({

	        //Set the entity availability to the same interval as the simulation time.
	        availability : new Cesium.TimeIntervalCollection([new Cesium.TimeInterval({
	            start : start,
	            stop : stop
	        })]),

	        //Use our computed positions
	        position : position,

	        //Automatically compute orientation based on position movement.
	        orientation : new Cesium.VelocityOrientationProperty(position),

	        //Load the Cesium plane model to represent the entity
	        model : {
	            uri : '/img/Cesium_Air.gltf',
	            minimumPixelSize : 100,
	            maximumScale : 300,
	            scaleByDistance : angleOfView
	        },


	        //Show the path as a pink line sampled in 1 second increments.
	        // path : {
	        //     resolution : 1,
	        //     material : new Cesium.PolylineGlowMaterialProperty({
	        //         glowPower : 0.1,
	        //         color : Cesium.Color.DARKGREY
	        //     }),
	        //     width : 10
	        // }
	    });
	}
	//删除飞机
	that.hidePlane = function () {
		viewer.entities.remove(plane_entity);
	}

    /*var imageryViewModels = [];
    imageryViewModels.push(new Cesium.ProviderViewModel({
         name : 'track1',
         iconUrl : Cesium.buildModuleUrl('/img/point.png'),
         tooltip : 'OpenStreetMap (OSM) is a collaborative project to create a free editable \
    map of the world.\nhttp://www.openstreetmap.org',
         creationFunction : function() {
             return Cesium.createOpenStreetMapImageryProvider({
                 url : 'https://a.tile.openstreetmap.org/'
             });
         }
     }));*/


    //轨迹测试数据		
		/* var trackArray = [
			[120.149884, 30.172466],
			[120.150124, 30.171886],
			[120.150564, 30.172036],
			[120.151230, 30.172126],
			[120.151599, 30.170868]
		];
		var timeArray = [
			'2017-11-21T00:00:00.000Z', 
			'2017-11-21T01:00:00.000Z',
			'2017-11-21T05:00:00.000Z',
			'2017-11-21T10:00:00.000Z',
			'2017-11-21T12:00:00.000Z'
		];*/

	// var dataArray_1 = [
	// 	{track:[120.149884, 30.172466],time:'2017-11-21T00:00:00.000Z'},
	// 	{track:[120.150124, 30.171886],time:'2017-11-21T01:00:00.000Z'},
	// 	{track:[120.150564, 30.172036],time:'2017-11-21T05:00:00.000Z'},
	// 	{track:[120.151230, 30.172126],time:'2017-11-21T10:00:00.000Z'},
	// 	{track:[120.151599, 30.170868],time:'2017-11-21T12:00:00.000Z'}
	// ]

	//trackArray 轨迹经纬度数组， timeArray 轨迹时间数组， image 轨迹显示类型图片
	that.czmlDSCollection = {};  //轨迹czmldatasource缓存对象
	that.trackPointInfo = {};  //轨迹信息点数据缓存
	//返回轨迹路径czml对象
	function getTrackCZML(sTime, eTime, data, type, image) {

		var startTime = new Date(sTime);
		var endTime = new Date(eTime);
		var timeDiff = endTime.getTime() - startTime.getTime();
		var lastTime = new Date(startTime.getTime() + timeDiff * 5);
		var endLng = data[data.length - 1].track[0];
		var endLat = data[data.length - 1].track[1];
		var trackHigh = type == 'track' ? 1 : 1.05;
		var perDiff = timeDiff / data.length;

		var perHigh = 50 / data.length;

		//czml 初始化
		var czml = [
		  {
		    id : "document",
		    name : "CZML Path",
		    version : "1.0",
		    clock: {
		        interval: startTime.toJSON() + '/' + lastTime.toJSON(),
		        currentTime: startTime.toJSON(),
		        multiplier: timeDiff / 10000
		    }
		  }
		];
		var pathType = {
			track:{
		      material : {
		          polylineOutline : {
		              color : {
		                  rgba : [39,170,55,255]
		              },
		              outlineColor : {
		                  rgba : [39,170,55,255]
		              },
		              outlineWidth : 5
		          }
		      },
		      width : 6,
		      leadTime : 0,
		      trailTime : timeDiff * 5 / 1000,
		      resolution : 5
		  },
			fellow:{
		      material : {
		          polylineOutline : {
		              color : {
		                  rgba : [255,172,0, 255]
		              },
		              outlineColor : {
		                  rgba : [255,172,0, 255]
		              },
		              outlineWidth : 5
		          }
		      },
		      width : 4,
		      leadTime : 0,
		      trailTime : timeDiff * 5 / 1000,
		      resolution : 5
		  }
		}
		//初始化轨迹
		var track = {
		  id : "track",
		  name : "track",
		  availability : startTime.toJSON() + '/' + lastTime.toJSON(),
		  path : pathType[type],
		  billboard : {
		      image : image,
		      scale : 0.2,
		      horizontalOrigin: 'CENTER',
		      verticalOrigin: 'BOTTOM',
		  },
		  position : {
		      epoch : startTime.toJSON(),
		      cartographicDegrees : []
		  }
		};
		czml.push(track);

		//加载轨迹和点
		for(var i = 0; i < data.length; i++) {

			var time = new Date(data[i].time);
			// var pointInterval = (time.getTime() - startTime.getTime()) / 1000;
			  var pointInterval = perDiff * (i + 1) / 1000;
			  var highInterval = perHigh * (i + 1);
				var i_str = i + 1 + "";
			  // czml.push({
			  //   id : "point" + i_str,
			  //   name : "point" + i_str,
			  //   availability : time.toJSON() + '/' + lastTime.toJSON(),
			  //   billboard : {
			  //       image : "img/point.png",
			  //       scale : 0.5,
			  //       eyeOffset: {
			  //           cartesian: [ 0.0, 5.0, 0.0 ]
			  //       }
			  //   },
			  //   // label : {
			  //   //     text : i_str,
			  //   //     scale : 0.5,
			  //   //     eyeOffset: {
			  //   //         cartesian: [ 0.0, 7.0, -1.0 ]
			  //   //     }
			  //   // },
			  //   position : {
			  //       epoch : startTime.toJSON(),
			  //       cartographicDegrees : [
			  //           pointInterval, data[i].track[0], data[i].track[1], 10,
			  //           timeDiff * 3 / 1000, data[i].track[0], data[i].track[1], 10
			  //       ]
			  //   }
			  // });

			  //添加到轨迹
			  czml[1].position.cartographicDegrees.push(pointInterval);
			  czml[1].position.cartographicDegrees.push(data[i].track[0] - 0);
			  czml[1].position.cartographicDegrees.push(data[i].track[1] - 0);
			  czml[1].position.cartographicDegrees.push(trackHigh);
		}

		// czml[1].position.cartographicDegrees.push(timeDiff * 5 / 1000);
		// czml[1].position.cartographicDegrees.push(data[data.length - 1].track[0] - 0);
		// czml[1].position.cartographicDegrees.push(data[data.length - 1].track[1] - 0);
		// czml[1].position.cartographicDegrees.push(trackHigh);

		return czml;
	}

	//返回轨迹信息点czml对象
	function getTrackPointsCZML(sTime, eTime, data, trackPoint_id) {
	var endTime = new Date(eTime);
	var startTime = new Date(sTime);
	var timeDiff = endTime.getTime() - startTime.getTime();
	var lastTime = new Date(startTime.getTime() + timeDiff * 5);

	//czml 初始化
	var czml = [
	  {
	    id : "document",
	    name : "CZML Path",
	    version : "1.0",
	    clock: {
	        interval: startTime.toJSON() + '/' + lastTime.toJSON(),
	        currentTime: startTime.toJSON(),
	        multiplier: timeDiff / 10000
	    }
	  }
	];

	//加载轨迹和点
	for(var i in data) {
		// var k = i < data.length - 1 ? i + 1 : i;
	 //  	var time = new Date(data[k].passTime);
	 //  	var pointInterval = (time.getTime() - startTime.getTime()) / 1000;
	 	pointInterval = 0;
	  	// var i_str = data[i].times.length + '';
	  	czml.push({
		    id : "point_" + trackPoint_id + "_" + i,
		    name : "point_" + trackPoint_id + "_" + i,
		    availability : startTime.toJSON() + '/' + lastTime.toJSON(),
		    billboard : {
		        image : "img/point.png",
		        scale : 0.5,
		        horizontalOrigin: 'CENTER',
		        verticalOrigin: 'BOTTOM',
		    },
		    // label : {
		    //     text : i_str,
		    //     scale : 0.5,
		    //     eyeOffset: {
		    //         cartesian: [ 0.0, 7.0, -1.0 ]
		    //     }
		    // },
		    position : {
		        epoch : startTime.toJSON(),
		        cartographicDegrees : [
		          pointInterval, data[i].camerJd - 0, data[i].camerWd - 0, 1,
		          timeDiff * 5 / 1000, data[i].camerJd - 0, data[i].camerWd - 0, 1
		        ]
		    }
	  	});

	}

	// console.log(czml);
	return czml;
	}

	function getTrackPointInfoById(pointId) {
		var idList = pointId.split('_');
		return {
			addr: idList[2],
			times: that.trackPointInfo[idList[1]][idList[2]].times,
			picture: that.trackPointInfo[idList[1]][idList[2]].picture
		};
	}

	//添加轨迹到viewer中，并返回轨迹路径id和轨迹信息点id
	//pathArray 轨迹路径点，dataArray 轨迹信息点， type 类型
	//return  [trackid，trackpointsid]
	that.getTrack = function(startTime, endTime, pathArray, dataArray,type, icon){
		console.log(startTime, endTime, pathArray, dataArray,type, icon, 111);
		var trackpointArray = DataService.mergeTrack(dataArray);
		var track_id = 't' + new Date().getTime();
		var trackPoint_id = 'tp' + new Date().getTime();
		that.trackPointInfo[trackPoint_id] = trackpointArray;
		//轨迹czml dataArray为轨迹路径点
		var czml_track = getTrackCZML(startTime, endTime, pathArray,type, '/img/ico/'+icon+'.png');
		//轨迹上点位czml dataArray为轨迹信息点
		var czml_point = getTrackPointsCZML(startTime, endTime, trackpointArray, trackPoint_id);
		var czmlDS_track = Cesium.CzmlDataSource.load(czml_track);
		var czmlDS_point = Cesium.CzmlDataSource.load(czml_point);

		czmlDS_track.then(function (data) {
		  that.czmlDSCollection[track_id] = data;
		  viewer.dataSources.add(data);
		})
		czmlDS_point.then(function (data) {
		  that.czmlDSCollection[trackPoint_id] = data;
		  viewer.dataSources.add(data);
		})
		return [track_id, trackPoint_id];
	}

	that.showTrack = function (id) {
		if(viewer.dataSources.indexOf(that.czmlDSCollection[id]) < 0) {
		  viewer.dataSources.add(that.czmlDSCollection[id]);
		}
	}

	that.removeTrack = function (id) {
		var status = viewer.dataSources.remove(that.czmlDSCollection[id]);
	}

	that.destoryAll = function () {
		var status = viewer.dataSources.removeAll();
		that.czmlDSCollection = {};
	}

}

